package com.itheima.controller;

import com.itheima.pojo.Result;
import com.itheima.utils.AliOssUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
public class FileUploadController {
    // 上传文件存储的目录
    private static final String UPLOAD_DIRECTORY = "upload";
    @PostMapping("/upload")
    public Result<String> handleFileUpload(@RequestParam("file") MultipartFile file) throws IOException {

        //--------------------上传到本地

//        if (file.isEmpty()) {
//            return new ResponseEntity<>("请选择要上传的文件", HttpStatus.BAD_REQUEST);
//        }
//
//        try {
//            // 获取上传文件的名称
//            String fileName = file.getOriginalFilename();
//            // 获取本地资源中的upload文件夹的路径
//            String uploadPath = System.getProperty("user.dir") + File.separator + UPLOAD_DIRECTORY;
//            // 创建目录（如果不存在）
//            File uploadDir = new File(uploadPath);
//            if (!uploadDir.exists()) {
//                uploadDir.mkdir();
//            }
//            // 将上传的文件保存到本地文件系统
//            FileCopyUtils.copy(file.getBytes(), new File(uploadPath + File.separator + fileName));
//            // 返回上传成功的响应
//            return ResponseEntity.ok("文件上传成功，保存路径为: " + uploadPath + File.separator + fileName);
//        } catch (IOException e) {
//            // 返回上传失败的响应
//            return new ResponseEntity<>("文件上传失败: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
//        }
//        --------------------------------


        //上传到阿里云oss
        String originalFilename = file.getOriginalFilename();
        // 保证文件名唯一
        String filename = UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));
        String url = AliOssUtil.uploadFile(filename,file.getInputStream());
        return Result.success(url);

    }
}
